<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='search'>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='冷库名称'>
              <a-input placeholder='请输入冷库名称' v-model='queryParams.name'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='冷库编码'>
              <a-input placeholder='请输入冷库编码' v-model='queryParams.code'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='成本中心'>
              <a-select v-model='queryParams.cost' placeholder='请选择成本中心'>
                <a-select-option v-for='(d,i) in costList' :key='d.id' :value='d.cost'>{{
                    d.cost_dictText
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
                <a-button type='primary' @click='search' icon='search'>查询</a-button>
                <a-button type='primary' @click='resetSearch' icon='reload' style='margin-left: 8px'>重置</a-button>
                <a @click='handleToggleSearch' style='margin-left: 8px'>
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button @click='addModalShow' type='primary' icon='plus'>新增</a-button>
      <a-button type='primary' icon='download' @click="handleExportXls('冷库主表')">导出</a-button>
      <a-upload name='file' :showUploadList='false' :multiple='false' :headers='tokenHeader' :action='importExcelUrl'
                @change='handleImportExcel'>
        <a-button type='primary' icon='import'>导入</a-button>
      </a-upload>
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='storehouseDeleteBatch(selectedRowKeys)'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'> 批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        size='middle'
        bordered
        rowKey='id'
        class='j-table-force-nowrap'
        :columns='columns'
        :dataSource='storehouseDataSource'
        :pagination='mainPagination'
        :loading='loading'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='handleTableChange'>

        <template slot='htmlSlot' slot-scope='text'>
          <div v-html='text'></div>
        </template>
        <template slot='imgSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无图片</span>
          <img v-else :src='getImgView(text)' height='25px' alt=''
               style='max-width:80px;font-size: 12px;font-style: italic;' />
        </template>
        <template slot='fileSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无文件</span>
          <a-button
            v-else
            :ghost='true'
            type='primary'
            icon='download'
            size='small'
            @click='uploadFile(text)'>
            下载
          </a-button>
        </template>

        <span slot='action' slot-scope='text, record'>
            <a @click='editModalShow(record)'>编辑</a>

            <a-divider type='vertical' />
            <a-dropdown>
              <a class='ant-dropdown-link'>更多 <a-icon type='down' /></a>
              <a-menu slot='overlay'>
                <a-menu-item>
                  <a-popconfirm title='确定删除吗?' @confirm='() => storehouseDelete(record.id)'>
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>

      </a-table>
    </div>

    <!--    <flowerstorehouse-modal ref="modalForm" @ok="modalFormOk"></flowerstorehouse-modal>-->
    <a-modal v-model:visible='addOrEditVisible' width='50%' :title='firstModalTitle' @ok='storehouseAddOrEdit'
             :maskClosable='false'>
      <div>
        <a-row>
          <a-col :span='12'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>所属单位：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input placeholder='自动生成' disabled v-model='storehouse.deptName' />
            </div>
          </a-col>

          <a-col :span='12'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>所属基地：</div>
            <div style='display: inline-block;width: 60%'>
              <!--              <a-input v-model='storehouse.baseId' placeholder='请选择所属基地' style='width: 100%'/>-->
              <j-dict-select-tag v-model='storehouse.baseId' dict-code='t_flower_planting_base,name,id'
                                 placeholder='请选择所属基地' style='width: 100%'></j-dict-select-tag>
            </div>
          </a-col>

          <a-col :span='12'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>冷库名称：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input v-model='storehouse.name' placeholder='请输入冷库名称' />
            </div>
          </a-col>
          <a-col :span='12'>
            <div style='display: inline-block'>冷库编码：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input v-model='storehouse.code' placeholder='自动生成' style='width: 100%' disabled />
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='12'>
            <div style='display: inline-block'>负责人：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input v-model='storehouse.person' placeholder='请输入负责人' style='width: 100%' />
            </div>
          </a-col>
          <a-col :span='12'>
            <div style='display: inline-block'>负责人编码：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input v-model='storehouse.personcode' placeholder='请输入负责人编码' style='width: 100%' />
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='12'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>成本中心：</div>
            <div style='display: inline-block;'>
              <a-select v-model='storehouse.cost' placeholder='请选择成本中心' style='width: 200px;'>
                <a-select-option v-for='(d,i) in costList' :key='d.id' :value='d.cost'>{{
                    d.cost_dictText
                  }}
                </a-select-option>
              </a-select>
            </div>
          </a-col>
        </a-row>
      </div>
      <a-divider />
      <div style='margin-top: -20px'>
        <div style='font-size: 20px;color: #0742f3;margin-bottom: 3px'>冷库人员关联</div>
        <a-button type='primary' icon='plus' @click='userModalShow'>新增</a-button>
        <div style='margin-top: 7px'>
          <a-table :columns='userColumns' :data-source='userDataSource'
                   bordered row-key='superId'
                   :loading='userLoading'>
            <template slot='operation' slot-scope='text, record'>
              <a-popconfirm v-if='userDataSource.length' title='确定删除?'
                            @confirm='() => userDelete(record.id)'>
                <a>删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </div>
      </div>
    </a-modal>
    <a-modal v-model:visible='selectUserVisible' width='60%' title='用户选择' @ok='userAdd'>
      <div style='margin-bottom: 10px'>
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block;width: 45px;'>账号：</div>
            <div style='display: inline-block;width: 70%'>
              <a-input v-model='queryUserParams.personcode' placeholder='请输入账号' allow-clear @change='searchUser' />
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;width: 80px;'>用户名：</div>
            <div style='display: inline-block;width: 70%'>
              <a-input v-model='queryUserParams.person' placeholder='请输入用户名' allow-clear @change='searchUser' />
            </div>
          </a-col>
          <a-col :span='8'>
            <a-button type='primary' icon='search' @click='searchUser'>
              查询
            </a-button>
          </a-col>
        </a-row>
      </div>
      <a-table :columns='selectUserColumns' :data-source='selectUserDataSource' bordered
               :loading='selectUserLoading'
               :row-selection="{selectedRowKeys: selectedRowKeys,type: 'checkbox',onChange:onUserSelectChange}"
               row-key='username'
               :pagination='selectUserPagination'
               @change='selectUserPaginationChange'
      ></a-table>
    </a-modal>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import FlowerStorehouseModal from './modules/FlowerStorehouseModal2'
import '@/assets/less/TableExpand.less'
import {
  getFlowerStorehouse,
  getFlowerStorehouseDetailByMainId,
  getFlowerCost,
  flowerStorehouseAdd,
  flowerStorehouseEdit,
  flowerStorehouseDelete,
  flowerStorehouseDeleteBatch, getUserList
} from '@/api/api'
import { flowerPreDelete, flowerPreDeleteBatch } from '../../api/api'

export default {
  name: 'FlowerStorehouseList',
  mixins: [JeecgListMixin],
  components: {
    FlowerStorehouseModal
  },
  data() {
    return {
      queryParams: {// 主页查询
        name: '',//冷库名称
        code: '',//冷库编码
        cost: ''//成本中心
      },
      description: '冷库主表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '所属单位',
          align: 'center',
          dataIndex: 'deptName'
        },
        {
          title: '冷库名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '冷库编码',
          align: 'center',
          dataIndex: 'code'
        }, {
          title: '成本中心',
          align: 'center',
          dataIndex: 'cost_dictText'
        },
        {
          title: '负责人',
          align: 'center',
          dataIndex: 'person'
        },
        {
          title: '负责人编码',
          align: 'center',
          dataIndex: 'personcode'
        },
        /*    {
              title: '状态',
              align: 'center',
              dataIndex: 'state',
              customRender: function (text) {
                let stateString = ''
                switch (text) {
                  case 0:
                    stateString = '正常'
                    break
                  case 1:
                    stateString = '删除'
                    break
                  default:
                    stateString = '未知'
                }
                return stateString
              },
            },*/
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createBy'
        },
        {
          title: '创建日期',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '更新人',
          align: 'center',
          dataIndex: 'updateBy'
        },
        {
          title: '更新日期',
          align: 'center',
          dataIndex: 'updateTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/flower/flowerStorehouse/list',
        delete: '/flower/flowerStorehouse/delete',
        deleteBatch: '/flower/flowerStorehouse/deleteBatch',
        exportXlsUrl: '/flower/flowerStorehouse/exportXls',
        importExcelUrl: 'flower/flowerStorehouse/importExcel'
      },
      dictOptions: {},
      addOrEditVisible: false,//是否打开新增或编辑的弹窗
      selectUserVisible: false,//是否打开用户选择的弹窗
      firstModalTitle: '',
      addOrEditFlag: 'add',//打开的弹窗是新增还是编辑的标识
      storehouse: {
        name: '',//冷库名称
        code: '',//冷库编码
        person: '',//负责人
        personcode: '',//负责人编码
        cost: ''//成本中心
      },
      userColumns: [// 第一个弹窗中的表头
        {
          title: '账号',
          dataIndex: 'personcode'
        },
        {
          title: '用户名',
          dataIndex: 'person'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 100,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      selectUserColumns: [// 第二个弹窗的表头
        {
          title: '账号',
          dataIndex: 'personcode'
        }, {
          title: '用户名',
          dataIndex: 'person'
        }
      ],
      storehouseDataSource: [],
      mainPagination: {// 主页表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      userPagination: {//选择用户弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      userDataSource: [],
      selectUserDataSource: [],
      selectUserPagination: {//选择用户弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      userLoading: false,//是否显示第一个弹窗中表格的加载状态
      selectUserLoading: false,//是否显示第二个弹窗中表格的加载状态
      queryUserParams: {// 用户选择弹窗的查询
        personcode: '',// 账号
        person: ''// 用户名
      },
      costList: [],//成本中心列表
      disabled: {// 第一个弹窗中各控件是否禁用
        code: false//冷库编码
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  mounted() {
    this.queryStorehouse()
    this.queryCost()
  },
  methods: {
    initDictConfig() {
    },
    search() {// 主页中根据条件查询
      this.loading = true
      this.storehouseDataSource.length = 0
      getFlowerStorehouse(this.queryParams).then(res => {
        if (res.success) {
          this.storehouseDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },
    resetSearch() {// 重置查询
      this.queryParams = {// 主页查询
        name: '',//冷库名称
        code: '',//冷库编码
        cost: ''//成本中心
      }
      this.search()
    },
    searchUser() {// 用户选择弹窗中的搜索用户
      let params = {
        pageNo: this.selectUserPagination.current,
        pageSize: this.selectUserPagination.pageSize,
        username: this.queryUserParams.personcode,
        realname: this.queryUserParams.person
      }
      getUserList(params).then(res => {
        if (res.success) {
          this.selectUserPagination.total = res.result.total
          this.selectUserDataSource = res.result.records

          this.selectUserDataSource.map(item => {//将personcode（账号）和person（用户名）封装进userList中的各用户对象中
            item.personcode = item.username
            item.person = item.realname
          })
        } else {
          this.$message.error(res.message)
        }
        this.selectUserLoading = false
      })
    },
    queryStorehouse() {//获取冷库
      this.storehouseDataSource.length = 0
      let params = {
        pageNo: this.mainPagination.current,
        pageSize: this.mainPagination.pageSize
      }
      getFlowerStorehouse(params).then(res => {
        if (res.success) {
          this.mainPagination.total = res.result.total
          this.storehouseDataSource = res.result.records
        }
      })
    },

    mainPaginationChange(pagination) {
      this.mainPagination.current = pagination.current
      this.mainPagination.pageSize = pagination.pageSize
      this.queryStorehouse()
    },
    addModalShow() {//打开第一个弹窗(新增)
      this.addOrEditFlag = 'add'
      this.firstModalTitle = '新增'
      this.storehouse = {
        name: '',//冷库名称
        code: '',//冷库编码
        person: '',//负责人
        personcode: '',//负责人编码
        cost: ''//成本中心
      }
      this.userDataSource = []
      this.queryCost()
      this.disabled = {// 第一个弹窗中各控件是否禁用
        code: false//冷库编码
      }
      this.addOrEditVisible = !this.addOrEditVisible
    },
    editModalShow(record) {//打开第一个弹窗(编辑)
      this.addOrEditFlag = 'edit'
      this.firstModalTitle = '编辑'
      this.storehouse = record
      this.userDataSource.length = 0
      this.queryFlowerStorehouseDetailByMainId(record.id)
      this.queryCost()
      this.disabled = {// 第一个弹窗中各控件是否禁用
        code: true//冷库编码
      }
      this.addOrEditVisible = !this.addOrEditVisible
    },
    userModalShow() {//打开第二个弹窗
      /*设置下面这两行是为了处理再次打开商品选择弹窗时，
      还会在界面上保留上次选择用户而实际上没有选择任何用户的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0

      this.selectUserPagination = {//选择用户弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
      this.queryUserList()
      this.selectUserVisible = !this.selectUserVisible
    },
    queryFlowerStorehouseDetailByMainId(id) {//获取第一个弹窗中的用户
      let params = {
        id: id
      }
      getFlowerStorehouseDetailByMainId(params).then(res => {
        if (res.success) {
          this.userDataSource = res.result
        }
      })
    },
    queryUserList() {// 查询所有用户
      this.selectUserLoading = true
      let params = {
        pageNo: this.selectUserPagination.current,
        pageSize: this.selectUserPagination.pageSize
      }
      getUserList(params).then(res => {
        if (res.success) {
          this.selectUserPagination.total = res.result.total
          this.selectUserDataSource = res.result.records

          //将personcode（账号）、person（用户名）封装进userList中的各用户对象中
          this.selectUserDataSource.map(item => {
            item.personcode = item.username
            item.person = item.realname
          })
        } else {
          this.$message.error(res.message)
        }
        this.selectUserLoading = false
      })
    },

    onUserSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法多选
      this.selectionRows = selectionRows
    },
    userAdd() {// 第二个弹窗中的确定选择用户
      //this.userDataSource = [...this.userDataSource, ...this.selectionRows]
      top:
        for (let i = 0; i < this.selectionRows.length; i++) {
          for (let item of this.userDataSource) {
            if (this.selectionRows[i].person === item.person) {
              this.$message.error(`该冷库已经关联了${item.person}用户`)
              break top //跳出最外层for循环
            }
          }
          let item = {}
          if (this.addOrEditFlag === 'add') {// 新增冷库的情况
            item.person = this.selectionRows[i].realname
            item.personcode = this.selectionRows[i].username
            item.personid = this.selectionRows[i].id
            this.userDataSource.push(item)
          } else {// 编辑冷库的情况
            item.mainid = this.storehouse.id
            item.person = this.selectionRows[i].realname
            item.personcode = this.selectionRows[i].username
            item.personid = this.selectionRows[i].id
            this.userDataSource.push(item)
          }
        }
      this.selectUserVisible = !this.selectUserVisible
    },
    selectUserPaginationChange(pagination) {
      this.selectUserPagination.current = pagination.current
      this.selectUserPagination.pageSize = pagination.pageSize
      this.queryUserList()
    },
    storehouseAddOrEdit() {// 确定新增或编辑冷库
      if (this.storehouse.name === '') {
        this.$message.error('请输入冷库名称')
      } else /*if (this.storehouse.code === '') {
        this.$message.error('请输入冷库编码')
      }else */if (this.storehouse.cost === '') {
        this.$message.error('请选择成本中心')
      } else {
        if (this.addOrEditFlag === 'add') {// 新增冷库的情况
          /*this.userDataSource.map(item=>{//将personid（用户id）封装进userDataSource中的各用户对象中
            item.personid = item.id
            delete item.id
          })*/
          this.storehouse.flowerStorehouseDetailList = this.userDataSource//将用户信息封装进storehouse中
          flowerStorehouseAdd(this.storehouse).then(res => {
            if (res.success) {
              this.queryStorehouse()
              this.$message.success('新增冷库成功')
            } else {
              this.$message.error(res.message)
            }
            this.addOrEditVisible = false
          })
        } else {// 编辑冷库的情况
          /*this.userDataSource.map(item=>{//将mainid(冷库id)、personid（用户id）封装进userDataSource中的各用户对象中
            item.mainid = this.storehouse.id
            item.personid = item.id
            delete item.id
          })*/

          this.storehouse.flowerStorehouseDetailList = this.userDataSource//将用户信息封装进storehouse中
          flowerStorehouseEdit(this.storehouse).then(res => {
            if (res.success) {
              this.queryStorehouse()
              this.$message.success('编辑冷库成功')
            } else {
              this.$message.error(res.message)
            }
            this.addOrEditVisible = false
          })
        }
      }
    },
    storehouseDelete(id) {
      flowerStorehouseDelete({ id: id }).then(res => {
        if (res.success) {
          this.queryStorehouse()
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    storehouseDeleteBatch(selectedRowKeys) {
      if (selectedRowKeys.length > 0) {
        let ids = ''
        for (let item of selectedRowKeys) {
          ids = ids + item + ','
        }
        flowerStorehouseDeleteBatch({ ids: ids }).then(res => {
          if (res.success) {
            this.queryStorehouse()
            this.selectedRowKeys.length = 0
            this.$message.success('批量删除成功')
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    userDelete(id) {
      const dataSource = [...this.userDataSource]
      this.userDataSource = dataSource.filter(item => item.id !== id)
    },
    queryCost() {
      getFlowerCost().then(res => {
        if (res.success) {
          this.costList = res.result
          this.costList.map(item => {//将costList中的各成本中心对象中封装进cost（成本中心编号）和cost_dictText（成本中心名称）
            item.cost = item.value
            item.cost_dictText = item.title
          })
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.ant-col {
  margin-top: 3px;
  height: 40px;
}
</style>